package com.everflourish.yeah100.act.markingsystem;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.TeacherShareAdapter;
import com.everflourish.yeah100.entity.marking.Teacher;
import com.everflourish.yeah100.entity.marking.TeacherModel;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lapism.searchview.SearchView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/1.
 * 时间：2016/7/1
 */
public class TeacherShareActivity extends BaseActivity {

    private Toolbar mToolBar;
    private RecyclerView mTeacherList;
    private ArrayList<TeacherModel> mList;
    private ArrayList<TeacherModel> mHaveChecklist;
    public boolean isSelfCreate;
    private TeacherShareAdapter mAdapter;
    private MarkingSystemRequest mRequest;
    private LoadDialog mLoadDialog;
    private SearchView mSearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_share);
        initData();
        initView();
        configView();
        setSearchView();
    }

    private void initData() {
        mRequest = MarkingSystemRequest.getInstance();
        mList = new ArrayList<TeacherModel>();
        mHaveChecklist = (ArrayList<TeacherModel>) getIntent()
                .getSerializableExtra(IntentUtil.TEACHER_LIST);
        isSelfCreate = getIntent().getBooleanExtra("isSelfCreate", true);
        mAdapter = new TeacherShareAdapter(mContext, TeacherShareActivity.this, mList, mQueue);
        if (mHaveChecklist != null) {
            mList.addAll(mHaveChecklist);
        }
    }

    private void initView() {
        mToolBar = (Toolbar) findViewById(R.id.teacher_toolbar);
        mTeacherList = (RecyclerView) findViewById(R.id.teacher_share_list);
        mSearchView = (SearchView) findViewById(R.id.teacher_share_searchView);
    }

    private void configView() {
        mToolBar.setTitle("共享老师");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishMenuActivity();
            }
        });

        mTeacherList.setLayoutManager(new LinearLayoutManager(mContext));
        mTeacherList.setAdapter(mAdapter);
        getTeacherShareListRequest();
    }

    private void setSearchView() {
        mSearchView.setVersion(SearchView.VERSION_MENU_ITEM);
        mSearchView.setVersionMargins(SearchView.VERSION_MARGINS_MENU_ITEM);
//        mSearchView.setVersionMargins(SearchView.THEME_LIGHT);
        mSearchView.setTextSize(16);
        mSearchView.setHint("搜索老师");
        mSearchView.setDivider(false);
        mSearchView.setVoice(false);
        mSearchView.setVoiceText("Set permission on Android 6+ !");
        mSearchView.setAnimationDuration(SearchView.ANIMATION_DURATION);
//        mSearchView.setShadowColor(ContextCompat.getColor(this, R.color.search_shadow_layout));
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mSearchView.close(true);
                Intent intent = new Intent(TeacherShareActivity.this,
                        TeacherSearchActivity.class);
                intent.putExtra(IntentUtil.CHECKED_TEACHERS, mList);
                intent.putExtra("condition", query.trim());
                intent.putExtra(IntentUtil.FLAG,
                        IntentUtil.ADD_FRIEND_ACTIVITY_FLAG);
                startActivityForResult(intent,
                        IntentUtil.ADD_FRIEND_ACTIVITY_FLAG);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    // 获取共享老师记录请求
    private void getTeacherShareListRequest() {
        mLoadDialog = LoadDialog.show(mContext, null, "加载中...", false);
        JsonObjectRequest request = mRequest.getShareTeacherRecordsRequest(
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getTeacherShareListListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取老师列表失败");
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    // 获取共享老师记录监听
    private void getTeacherShareListListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray("shareTeacherRecords");
                Gson gson = new Gson();
                Type type = new TypeToken<List<Teacher>>() {
                }.getType();
                List<Teacher> teachersList = gson.fromJson(
                        jsonArray.toString(), type);
                setTeacherList(teachersList);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext,
                        R.string.mistakenotebook_101399_999999E);
            } else {
                MyToast.showShort(mContext, "获取老师列表失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "获取老师列表失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    private void setTeacherList(List<Teacher> teachersList) {
        for (Teacher t : teachersList) {
            if (!hasTeacher(t)) {
                TeacherModel teacherModel = new TeacherModel();
                teacherModel.setTeacher(t);
                teacherModel.setIsCheck(false);
                mList.add(teacherModel);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    private boolean hasTeacher(Teacher t) {
        boolean hasTeacher = false;
        for (TeacherModel model : mList) {
            Teacher teacher = model.getTeacher();
            if (t.getUserId().equals(teacher.getUserId())) {// 判断id
                hasTeacher = true;
                break;
            }
        }
        return hasTeacher;
    }

    /**
     * 设置关闭activity的数据
     */
    private void finishMenuActivity() {
        Intent intent = TeacherShareActivity.this.getIntent();
        intent.putExtra(IntentUtil.TEACHER_LIST, mList);
        TeacherShareActivity.this.setResult(RESULT_OK, intent);
        TeacherShareActivity.this.finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_teacher, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.teacher_action_search:
                mSearchView.open(true, item);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IntentUtil.ADD_FRIEND_ACTIVITY_FLAG) {
            if (resultCode == MarkingMenuActivity.RESULT_OK) {
                ArrayList<TeacherModel> mTeacherNewChecks = (ArrayList<TeacherModel>) data
                        .getSerializableExtra(IntentUtil.FRIENDS);
                ArrayList<TeacherModel> mTempTeacherModelList = new ArrayList<TeacherModel>();
                mTempTeacherModelList.addAll(mTeacherNewChecks);
                if (mTeacherNewChecks != null) {
                    for (TeacherModel teacherModel : mTempTeacherModelList) {
                        if (isSelfCreate) {
                            teacherModel.setIsDelete(true);
                        } else {
                            teacherModel.setIsDelete(false);
                        }
                        for (TeacherModel t : mList) {
                            if (t.getTeacher().getUserId().equals(teacherModel.getTeacher().getUserId())) {
                                mTeacherNewChecks.remove(teacherModel);
                            }
                        }
                    }
                    mList.addAll(mTeacherNewChecks);
                }
                mAdapter.notifyDataSetChanged();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}
